using WeatherMcpClient.Controllers;
using WeatherMcpClient.Services;
using WeatherMcpClient.Views;
using System;
using System.Threading.Tasks;
using System.IO;
using System.Net;

namespace WeatherMcpClient
{
    class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("🌤️ Weather HTTP Client - 天气查询工具");
            Console.WriteLine("=====================================");
            Console.WriteLine();

            var httpClient = new HttpClient();

            // 获取服务器地址
            string serverUrl = GetServerUrl();

            // 选择运行模式
            Console.WriteLine("请选择运行模式:");
            Console.WriteLine("1. 控制台模式 (Console Mode)");
            Console.WriteLine("2. 浏览器模式 (Browser Mode)");
            Console.Write("请输入选择 (1-2): ");

            var choice = Console.ReadLine();

            try
            {
                if (choice == "2")
                {
                    // 浏览器模式
                    await RunBrowserModeAsync(httpClient, serverUrl);
                }
                else
                {
                    // 控制台模式（默认）
                    await RunConsoleModeAsync(httpClient, serverUrl);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 运行出错: {ex.Message}");
                Console.WriteLine("按任意键退出...");
                Console.ReadKey();
            }
        }

        static string GetServerUrl()
        {
            Console.WriteLine("🌐 服务器配置");
            Console.WriteLine("=============");
            Console.WriteLine("1. 使用默认地址 (localhost:5205)");
            Console.WriteLine("2. 输入自定义服务器地址");
            Console.WriteLine("3. 自动检测网络地址");
            Console.Write("请选择 (1-3): ");

            var choice = Console.ReadLine();

            switch (choice)
            {
                case "2":
                    Console.Write("请输入服务器地址 (格式: http://IP:端口): ");
                    var customUrl = Console.ReadLine()?.Trim();
                    if (!string.IsNullOrEmpty(customUrl))
                    {
                        return customUrl;
                    }
                    break;
                case "3":
                    var localIP = GetLocalIPAddress();
                    if (!string.IsNullOrEmpty(localIP))
                    {
                        var autoUrl = $"http://{localIP}:5205";
                        Console.WriteLine($"🔍 检测到本地IP: {localIP}");
                        Console.WriteLine($"🌐 自动配置地址: {autoUrl}");
                        return autoUrl;
                    }
                    break;
            }

            return "http://localhost:5205";
        }

        static string GetLocalIPAddress()
        {
            try
            {
                var host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (var ip in host.AddressList)
                {
                    if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        return ip.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"⚠️ 无法获取本地IP地址: {ex.Message}");
            }
            return null;
        }

        static async Task RunConsoleModeAsync(HttpClient httpClient, string serverUrl)
        {
            Console.WriteLine("🖥️ 启动控制台模式...");
            Console.WriteLine($"正在连接到服务器: {serverUrl}");

            IWeatherService weatherService = new WeatherService(httpClient, serverUrl);
            IWeatherView consoleView = new ConsoleWeatherView();
            var consoleController = new WeatherController(weatherService, consoleView);
            
            await consoleController.RunAsync();
        }

        static async Task RunBrowserModeAsync(HttpClient httpClient, string serverUrl)
        {
            Console.WriteLine("🌐 启动浏览器模式...");
            Console.WriteLine($"正在连接到服务器: {serverUrl}");

            IWeatherService weatherService = new WeatherService(httpClient, serverUrl);
            
            // 检查服务端连接
            if (!await weatherService.CheckHealthAsync())
            {
                Console.WriteLine("❌ 无法连接到天气服务");
                Console.WriteLine($"请确保服务端正在运行: dotnet run --urls={serverUrl}");
                Console.WriteLine("按任意键退出...");
                Console.ReadKey();
                return;
            }

            Console.WriteLine("✅ 成功连接到天气服务");
            Console.WriteLine();
            Console.WriteLine("🌐 正在启动浏览器...");
            Console.WriteLine("请确保您的默认浏览器已安装");
            Console.WriteLine();

            try
            {
                // 获取项目根目录（从当前执行目录向上查找）
                var currentDir = Directory.GetCurrentDirectory();
                var projectRoot = FindProjectRoot(currentDir);
                var htmlPath = Path.Combine(projectRoot, "Views", "weather.html");
                
                Console.WriteLine($"🔍 当前目录: {currentDir}");
                Console.WriteLine($"🔍 项目根目录: {projectRoot}");
                Console.WriteLine($"🔍 HTML文件路径: {htmlPath}");
                Console.WriteLine();
                
                if (File.Exists(htmlPath))
                {
                    // 创建临时HTML文件，替换API地址
                    var tempHtmlPath = CreateTempHtmlFile(htmlPath, serverUrl);
                    
                    // 使用系统默认浏览器打开HTML文件
                    var startInfo = new System.Diagnostics.ProcessStartInfo
                    {
                        FileName = tempHtmlPath,
                        UseShellExecute = true
                    };
                    
                    System.Diagnostics.Process.Start(startInfo);
                    
                    Console.WriteLine("✅ 浏览器已启动");
                    Console.WriteLine($"📁 HTML文件路径: {tempHtmlPath}");
                    Console.WriteLine($"🔗 服务端地址: {serverUrl}");
                    Console.WriteLine();
                    Console.WriteLine("💡 提示:");
                    Console.WriteLine("- 在浏览器中点击城市名称可快速填充坐标");
                    Console.WriteLine("- 支持当前天气和3天预报查询");
                    Console.WriteLine("- 支持批量查询多个城市");
                    Console.WriteLine();
                    Console.WriteLine("按任意键退出程序...");
                    Console.ReadKey();
                    
                    // 清理临时文件
                    try
                    {
                        File.Delete(tempHtmlPath);
                    }
                    catch
                    {
                        // 忽略清理错误
                    }
                }
                else
                {
                    Console.WriteLine("❌ 找不到HTML文件");
                    Console.WriteLine($"期望路径: {htmlPath}");
                    Console.WriteLine();
                    Console.WriteLine("🔧 解决方案:");
                    Console.WriteLine("1. 确保Views文件夹中包含weather.html文件");
                    Console.WriteLine("2. 或者手动打开以下文件:");
                    
                    // 尝试多个可能的路径
                    var possiblePaths = new[]
                    {
                        Path.Combine(currentDir, "Views", "weather.html"),
                        Path.Combine(currentDir, "..", "..", "..", "Views", "weather.html"),
                        Path.Combine(currentDir, "..", "Views", "weather.html"),
                        Path.Combine(Directory.GetCurrentDirectory(), "Views", "weather.html")
                    };
                    
                    foreach (var path in possiblePaths)
                    {
                        var fullPath = Path.GetFullPath(path);
                        if (File.Exists(fullPath))
                        {
                            Console.WriteLine($"✅ 找到文件: {fullPath}");
                            Console.WriteLine("请手动在浏览器中打开此文件");
                            break;
                        }
                        else
                        {
                            Console.WriteLine($"❌ 尝试路径: {fullPath}");
                        }
                    }
                    
                    Console.WriteLine("按任意键退出...");
                    Console.ReadKey();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 启动浏览器失败: {ex.Message}");
                Console.WriteLine("请手动打开以下文件:");
                Console.WriteLine($"📁 {Path.Combine(Directory.GetCurrentDirectory(), "Views", "weather.html")}");
                Console.WriteLine("按任意键退出...");
                Console.ReadKey();
            }
        }

        static string CreateTempHtmlFile(string originalPath, string serverUrl)
        {
            try
            {
                var htmlContent = File.ReadAllText(originalPath);
                var tempPath = Path.Combine(Path.GetTempPath(), $"weather_{Guid.NewGuid()}.html");
                
                // 替换API地址
                htmlContent = htmlContent.Replace("const API_BASE = 'http://localhost:5205';", $"const API_BASE = '{serverUrl}';");
                
                File.WriteAllText(tempPath, htmlContent);
                return tempPath;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"⚠️ 创建临时文件失败: {ex.Message}");
                return originalPath;
            }
        }

        static string FindProjectRoot(string currentDir)
        {
            // 从当前目录开始向上查找，直到找到包含.csproj文件的目录
            var dir = new DirectoryInfo(currentDir);
            
            while (dir != null)
            {
                if (dir.GetFiles("*.csproj").Length > 0)
                {
                    return dir.FullName;
                }
                dir = dir.Parent;
            }
            
            // 如果找不到，返回当前目录
            return currentDir;
        }
    }
}

